#include "serverconnectionadapter.h"

ServerConnectionAdapter::ServerConnectionAdapter(QObject *parent)
	: QObject(parent)
{
	manager = new QNetworkAccessManager();
}

ServerConnectionAdapter::ServerConnectionAdapter()
{
	manager = new QNetworkAccessManager();
}

ServerConnectionAdapter::~ServerConnectionAdapter()
{
	delete manager;
	socket.close();
}

bool ServerConnectionAdapter::start(QString & address, quint16 port)
{
	QEventLoop eventLoop;
	QString url = "http://" + address +  "/server.php";
	r = manager->get(QNetworkRequest(QUrl(url)));
	connect(r, SIGNAL(finished()), &eventLoop, SLOT(quit()));
	eventLoop.exec();

	QHostAddress addr(address);
	socket.connectToHost(addr, port);

	if (socket.waitForConnected()) {
		return true;
	}
	return false;
}

bool ServerConnectionAdapter::transfer(QString & string) {
	char buf[20000] = "";
	strcpy(buf, string.toUtf8().data());

	int k = socket.write(buf, string.length()+1);
	if (socket.waitForBytesWritten ()) {
		return true;
	}
	else {
		return false;
	}
}


QString ServerConnectionAdapter::read() {
	char result[20000] = "";
	char number[10] = "";
	int k = 0;
	bool flag = true;

	if (socket.waitForReadyRead ()) {

		int l = socket.read(number, socket.bytesAvailable());
		k = atoi(number);

		transfer(QString("1"));
		
		while (flag && socket.waitForReadyRead()) {
			char buf[20000] = "";
			l = socket.read(buf, socket.bytesAvailable());
			if (l < k) {
				k -= l;
				strcat(result, buf);
			}
			else {
				strcat(result, buf);
				flag = false;
			}
		}
	}

	return QString::fromUtf8(result);
}